package cn.iocoder.yudao.module.system.util;

import cn.iocoder.yudao.framework.common.pojo.wework.WXTokenResponse;
import cn.iocoder.yudao.framework.common.pojo.wework.WeworkMessageSendReq;
import cn.iocoder.yudao.framework.common.pojo.wework.WeworkMessageSendResponse;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.common.util.spring.SpringContextUtils;
import cn.iocoder.yudao.framework.redis.utils.RedisUtils;
import cn.iocoder.yudao.framework.web.config.MyWeworkProperties;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * 通知消息工具类
 */
@Slf4j
public class NotifyUtils {

    /**
     * 企业微信获取access_token
     */
    public static final String WEWORK_GET_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";

    /**
     * 企业微信消息推送url
     */
    private static final String SEND_MESSAGE_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";

    private static MyWeworkProperties myWeworkProperties;

    static {
        myWeworkProperties = SpringContextUtils.getBean("myWeworkProperties");
    }

    /**
     * 给企业微信发送给通知
     * @param req 请求参数
     * @return
     */
    public static WeworkMessageSendResponse sendWeworkMessage(WeworkMessageSendReq req){
        String token = getToken();
        String sync = OkHttpUtils.builder().url(SEND_MESSAGE_URL + token)
                .specialPost(JsonUtils.toJsonString(req))
                .sync();
        return JsonUtils.parseObject(sync, WeworkMessageSendResponse.class);
    }

    /**
     * 获取企业微信外部联系人应用授权码
     *
     * @return
     */
    public static String getToken() {
        String token = RedisUtils.getString(myWeworkProperties.getTokenKey());
        if (StringUtils.isBlank(token)) {
            WXTokenResponse response = getWXToken();
            if (response.getErrcode() != 0) {
                for (int i = 0; i < 3; i++) {
                    try {
                        Thread.sleep(10000);
                        WXTokenResponse res = getWXToken();
                        System.out.println("第" + i + "重试");
                        if (res.getErrcode() == 0) {
                            RedisUtils.setStringWithExpiration(myWeworkProperties.getTokenKey(), res.getAccess_token(), res.getExpires_in());
                            token = res.getAccess_token();
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            } else {
                token = response.getAccess_token();
                RedisUtils.setStringWithExpiration(myWeworkProperties.getTokenKey(), response.getAccess_token(), response.getExpires_in());
            }
        }
        return token;
    }

    /**
     * 获取企业微信授权码
     *
     * @return
     */
    private static WXTokenResponse getWXToken() {
        String sync = OkHttpUtils.builder().url(WEWORK_GET_TOKEN_URL)
                .addParam("corpid", myWeworkProperties.getCropId())
                .addParam("corpsecret", myWeworkProperties.getSecret())
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .get()
                .sync();
        return JsonUtils.parseObject(sync, WXTokenResponse.class);
    }
}
